#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "../comm/Log.hpp"
#include "../comm/util.hpp"



namespace runnerNs {
    using namespace logNs;
    using namespace utilNs;
    class Runner {
    public :
        static void SetLimit(int cpu_limit, int mem_limit) {
            // 设置CPU时长
            struct rlimit cpu_rlimit;
            cpu_rlimit.rlim_max = RLIM_INFINITY;
            cpu_rlimit.rlim_cur = cpu_limit;
            setrlimit(RLIMIT_CPU, &cpu_rlimit);

            // 设置内存大小
            struct rlimit mem_rlimit;
            mem_rlimit.rlim_max = RLIM_INFINITY;
            mem_rlimit.rlim_cur = mem_limit * 1024 * 1024; //转化成为KB
            setrlimit(RLIMIT_AS, &mem_rlimit);
        }
        static int Run(const std::string& file_name, int cpu_limit, int mem_limit) {
            // 获得可执行程序名
            std::string execute = PathUtil::Exe(file_name);

            std::string stdin_file = PathUtil::Stdin(file_name);
            std::string stdout_file = PathUtil::Stdout(file_name);
            std::string stderr_file = PathUtil::Stderr(file_name);

            // 打开这三个文件
            umask(0);
            int stdin_fd = open(stdin_file.c_str(), O_CREAT | O_RDONLY, 0664);
            int stdout_fd = open(stdout_file.c_str(), O_CREAT | O_WRONLY, 0664);
            int stderr_fd = open(stderr_file.c_str(), O_CREAT | O_WRONLY, 0664);
            if (stdin_fd < 0 || stdout_fd < 0 || stderr_fd < 0) {
                LOG(Error) << "内部错误，打开文件失败" << std::endl;
                return -1; // 表示打开文件失败
            }

            pid_t id = fork();
            
            if (id < 0) {
                // 创建子进程失败
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                LOG(Error) << "内部错误，创建子进程失败" << std::endl;
                return -2;
            } else if (id == 0) {
                // 子进程
                dup2(stdin_fd, 0);
                dup2(stdout_fd, 1);
                dup2(stderr_fd, 2);

                // 设置程序运行的时间和空间限制
                SetLimit(cpu_limit, mem_limit);
                // 执行程序替换，运行程序
                execlp(execute.c_str(), execute.c_str(), nullptr);
                // 执行程序替换失败
                LOG(Error) << "内部错误，执行程序替换失败" << std::endl;
                exit(-1);
            } else {
                // 父进程
                close(stdin_fd);
                close(stdout_fd);
                close(stderr_fd);
                int status = 0;
                // 等待子进程
                pid_t rid = waitpid(id, &status, 0);
                if (rid = id) {
                    LOG(Debug) << "运行成功，退出状态码为: " << (status & 0x7F) << std::endl;
                    return status & 0x7F;
                }
            }
            LOG(Debug) << "运行成功" << std::endl;
            return 0;
        }
    };
};